"""
@Project ：zzzr_api_test 
@File    ：assert_.py
@IDE     ：PyCharm 
@Author  ：ZSR
@Date    ：2023/2/27 22:21
断言格式 ["1=='1'", "cc=='dad'", "12 in '123'", 'ig in $.lpl.ig']
"""

from jsonpath import jsonpath
from tool.log import logger
from tool.mysql_ import mysql_db


class Assert:
    @classmethod
    def assert_response(cls, assert_list: list, api_response: dict):
        new_assert_list = []
        for i in assert_list:
            if '$.' in i:
                # 获取$的索引位置
                wz = i.find('$')
                # 切片出表达式
                json_path = i[wz:len(i) - 1]
                # 把表达式转换为值
                value = jsonpath(api_response, json_path)
                if not value:
                    logger.error(f'\n断言表达式提取失败，请检查参数\n接口返回结果是:{api_response}\n提取表达式是：\n{json_path}')
                    return False
                value = value[0]
                # 用值把表达式替换掉（注意这个需要用变量接住这个替换的新值）
                i = i.replace(json_path, value)
            # 处理断言sql
            if 'sql-' in i:
                """
                1=="sql-SELECT title FROM case_test where id=2"
                要切片sql语句 SELECT title FROM case_test where id=2
                并且把查询结果替换掉sql语句
                """
                wz = i.find('-')
                sql = i[wz + 1:len(i) - 1]
                # 需要被替换的完整目标，“sql-SELECT title FROM case_test where id=2”
                i = i.replace('sql-' + sql, mysql_db.select_db(sql))
            new_assert_list.append(i)
        logger.info(f'\n断言表达式新列表：\n{new_assert_list}')
        # 判断每个断言的成功或者失败
        assert_result_list = []
        for i in new_assert_list:
            assert_result = eval(i)
            assert_result_list.append(assert_result)
        logger.info(f'\n断言结果列表:\n{assert_result_list}')
        # 如果断言结果列表里面有一个失败，那就断言失败
        if False in assert_result_list:
            return False
        return True


if __name__ == '__main__':
    print(Assert.assert_response(["'12' in '123'", '"ig" == "$.ig"', '1 == 1'], {'id': 1, 'ig': 'TheShy'}))
